<template>
    <div class="edit-popup">
        <el-dialog
            v-model="visible"
            :title="formData.id ? '编辑城市' : '新增城市'"
            :width="600"
            @close="handleClose"
        >
            <el-form
                ref="formRef"
                :model="formData"
                :rules="formRules"
                label-width="100px"
            >
                <el-form-item label="城市名称" prop="name">
                    <el-input v-model="formData.name" placeholder="请输入城市名称" clearable />
                </el-form-item>
                <el-form-item label="拼音" prop="pinyin">
                    <el-input v-model="formData.pinyin" placeholder="请输入城市拼音" clearable />
                </el-form-item>
                <el-form-item label="行政区划" prop="area_code">
                    <el-input v-model="formData.area_code" placeholder="请输入行政区划代码" clearable />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="handleClose">取 消</el-button>
                    <el-button type="primary" :loading="loading" @click="handleSubmit">
                        确 定
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup>
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { citySave } from '@/api/supervise/city'

const emit = defineEmits(['success', 'close'])
const formRef = shallowRef<FormInstance>()
const visible = ref(false)
const loading = ref(false)

const formData = reactive({
    id: '',
    name: '',
    pinyin: '',
    area_code: ''
})

const formRules: FormRules = {
    name: [{ required: true, message: '请输入城市名称', trigger: 'blur' }],
    pinyin: [{ required: true, message: '请输入城市拼音', trigger: 'blur' }],
    area_code: [{ required: true, message: '请输入行政区划代码', trigger: 'blur' }]
}

const handleClose = () => {
    visible.value = false
    emit('close')
}

const open = (type = 'add') => {
    visible.value = true
    if (type === 'add') {
        formData.id = ''
        formData.name = ''
        formData.pinyin = ''
        formData.area_code = ''
    }
}

const getDetail = async (row: any) => {
    Object.assign(formData, row)
}

const handleSubmit = async () => {
    await formRef.value?.validate()
    loading.value = true
    try {
        await citySave(formData)
        ElMessage.success('保存成功')
        emit('success')
        handleClose()
    } catch (error) {
        console.error('保存失败:', error)
    } finally {
        loading.value = false
    }
}

defineExpose({
    open,
    getDetail
})
</script>